/**
 * @资源路由
 * api.get('/index', IndexController.index)
 * api.get('/index/create', IndexController.create)
 * api.post('/index', IndexController.store)
 * api.get('/index/:id', IndexController.show)
 * api.get('/index/:id/edit', IndexController.edit)
 * api.put('/index/:id', IndexController.save)
 * api.get('/index/:id/destroy', IndexController.destroy)
 * 
 */



const Router = require('koa-router')
const IndexController = require('../app/Api/v1/IndexController')
const AuthController = require('../app/Api/v1//AuthController')
const auth = require('../app/Middlewares/Auth')
class Api {
    constructor() {
        this.$api = new Router({prefix: "/v1"})
        this.$api.use(auth)
        this.init()
        this.routes()
        return this.$api
    }

    /**
     * 初始化路由 加载资源路由
     * 
     * @memberof Api
     */
    async init () {
        await this.resource('index', IndexController)
    }
    // 定义普通路由
    async routes() {
        this.$api.get('/', async function (ctx, next) {
            ctx.body = 'Hello world'
        })
        this.$api.post('/authorize', AuthController.authorize)
        this.$api.get('/authorize/user', AuthController.user)

    }

    /**
     * 生成资源路由
     * 
     * @param {any} name 
     * @param {any} controller 
     * @memberof Api
     */
    async resource (name, controller) {
        this.$api.get(`/${name}`, controller.index)
        this.$api.get(`/${name}/create`,  controller.create)
        this.$api.post(`/${name}`,  controller.store)
        this.$api.get(`/${name}/:id`,  controller.show)
        this.$api.get(`/${name}/:id/edit`,  controller.edit)
        this.$api.put(`/${name}/:id`,  controller.save)
        this.$api.get(`/${name}/:id/destroy`,  controller.destroy)
    }
    
}

module.exports = new Api()
